$(function () {
  let laypage = layui.laypage;

  // 查询参数
  let q = {
    page: 1,
    limit: 10,
    cateid: 1,
  };

  homePage();
  getRenderArt();
  getRenderHot();
  getRenderNew();
  getNavSkip();
  getSkip();
  userCenter();

  // 用户中心和退出
  function userCenter() {
    // 没有token的时候隐藏用户中心和退出
    if (localStorage.getItem('token')) {
      let str = `
           <a href="user.html" id="user"><i class="fa fa-user"></i>&nbsp;用户中心</a>
           <a href="javascript:;" class="quit"><i></i>&nbsp;退出</a>`;
      $('.slinks').html(str);
    } else {
      let str = `
            <a href="login.html"><i class="fa fa-hand-o-right"></i>&nbsp;登录</a> |
            <a href="reg.html"><i class="fa fa-registered"></i>&nbsp;注册</a>`;
      $('.slinks').html(str);
    }
    $('#user').on('click', function (e) {
      e.preventDefault();
      if (localStorage.getItem('token')) {
        location.href = 'user.html';
      } else {
        location.href = 'login.html';
      }
    });
    $('.quit').on('click', function (e) {
      layer.confirm('你确定要退出吗?', { icon: 3, title: '退出提示' }, function (index) {
        localStorage.removeItem('token');
        location.reload();

        layer.close(index);
      });
    });
  }
  // 首页和全局数据
  function homePage() {
    axios({
      method: 'GET',
      url: '/index/index',
    }).then(function (res) {
      console.log(res);
      // 导航栏
      let strNav = res.data.data.allCate
        .map(item => {
          return `
            <li class="menu-item menu-item-type-taxonomy menu-item-object-category">
                <a href="list.html" id=${item.id}><span class="fa fa-bullhorn iconfont ${item.icon}"></span>${item.catename}</a>
            </li>
            `;
        })
        .join('');
      $('#nav').append(strNav);
      // 首页轮播图
      let strSwipper = res.data.data.banner
        .map(item => {
          return `
                <div class="swiper-slide" >
                    <a target="_blank" href=${item.advimglink}>
                        <img class="thumb" src='http://124.223.14.236:8060/${item.advimgsrc}'>
                        <h4>${item.advimgdesc}</h4>
                    </a>
                </div> `;
        })
        .join('');
      $('.swiper-wrapper').html(strSwipper);
      swiper();
      // 右侧广告位
      let advStr = res.data.data.sideBanner
        .map(item => {
          return `
            <a href=${item.advimglink} rel="nofollow" target="_blank" title=${item.advimgdesc}>
            <img class="g430" style="width:360px;height:133px;" src="http://124.223.14.236:8060/${item.advimgsrc}" alt=${item.advimgdesc}>
            </a>
            `;
        })
        .join('');
      $('.textwidget').html(advStr);
      // 热门标签
      let allTag = res.data.data.allTag
        .map(item => {
          return `
            <li><a title="" href="">${item.tagname}</a></li>
            `;
        })
        .join('');
      $('.widget_tags_inner').html(allTag);
      // 友情链接
      let allLink = res.data.data.allLink
        .map(item => {
          return `
            <li>
                <a href=${item.url}>
                    <img src="http://124.223.14.236:8060/${item.img}" alt="">
                    <p>${item.des}</p>
                </a>
            </li>
            `;
        })
        .join('');
      $('.widget_comments ul').html(allLink);
      // 底部友情链接
      let footerLink = res.data.data.allLink
        .map(item => {
          return `<a href=${item.url} title="百度">${item.des}</a> <span>|</span>`;
        })
        .join('');
      $('.footer .link').append(footerLink);
    });
  }
  //热门文章
  function getRenderArt() {
    axios({
      method: 'GET',
      url: '/index/recommend',
    }).then(function (res) {
      // console.log(res);
      let str = res.data.data.list
        .map(item => {
          return `
            <li>
                <a target="_blank" href="javascript:;" class='skipList' id=${item.id} data-catename=${item.catename}>
                    <span class="thumbnail">
                        <img src="http://124.223.14.236:8060/${item.pic}" class="thumb" />
                    </span>
                    <span class="text">${item.title}</span>
                    <span class="text-muted post-views">阅读(${item.click})</span>
                </a>
          </li> `;
        })
        .join('');
      $('.items-02').html(str);
    });
  }
  // 热门推荐
function getRenderHot() {
    axios({
      method: 'GET',
      url: '/index/hot',
    }).then(function (res) {
      // console.log(res);
      let str = res.data.data.list
        .map(item => {
          return `
            <li class="item">
                <a  href="" id=${item.id} class='skipList' data-catename=${item.catename}>
                    <img src='http://124.223.14.236:8060/${item.pic}' />
                    ${item.title}
                </a>
            </li>
            `;
        })
        .join('');
      $('.sticky ul').html(str);
    });

  }
  // 最近更新
  function getRenderNew() {
    axios({
      method: 'GET',
      url: '/index/new',
      params: q,
    }).then(function (res) {
      // console.log(res);
      $('.pull-right').html(`24小时更新：${res.data.data.num_day}篇 &nbsp; &nbsp; 一周更新：${res.data.data.num_week}篇`);
      let str = res.data.data.list.data
        .map(item => {
          return `
         <article class="excerpt excerpt-one">
          <header>
            <a class="cat label label-important" href="javascript:;">热门<i class="label-arrow"></i></a>
            <h2>
              <a href="javascript:;" class='skipList' id=${item.id} data-catename=${item.catename} title=${item.title}>${item.title}</a>
            </h2>
          </header>
          <p class="text-muted time">
            <a href="">悦享·编辑</a> 发布于 ${time(item.create_date)}
          </p>
          <p class="focus">
            <a target="_blank" href="http://blog.weknow.cn/474.shtml" class="thumbnail">
              <span class="item"><span class="thumb-span"><img src="http://124.223.14.236:8060/${item.pic}"
                    class="thumb" /></span></span></a>
          </p>
          <p class="note">${item.description}</p>
          <p class="text-muted views">
            <span class="post-views">阅读(${item.click})</span>
            <span class="post-comments">评论(0)</span>
            <a href="javascript:;" >
              <i class="fa fa-thumbs-up"></i>赞 (<span id="lovenum">${item.lovenum}</span>)
            </a>
            <span class="post-tags">标签：
              <a href="" rel="tag">${item.keywords}</a> /
          </p>
        </article>
            `;
        })
        .join('');
      $('.recent').html(str);
      // 调用渲染分页的方法
      renderPage(res.data.data.list.count);
    });
  }
  // 分页器函数
  function renderPage(totle) {
    // console.log(totle);
    // 调用layerPage方法
    laypage.render({
      elem: 'pageBox',
      count: totle,
      limit: q.limit,
      curr: q.page,
      layout: ['page', 'prev', 'next', 'count'],
      theme: '#ff7267',
      jump: function (obj, first) {
        //obj包含了当前分页的所有参数，比如：
        q.page = obj.curr;
        //首次不执行
        if (!first) {
          //调用渲染方法渲染最新列表
          getRenderNew();
        }
      },
    });
  }
  // 导航栏跳转
  function getNavSkip() {
    $('#nav').on('click', 'a', function (e) {
      e.preventDefault();
      window.open('list.html?id=' + $(this).attr('id'));
    });
  }
  // 点击跳转详情页
  function getSkip() {
    $('.items-02,.sticky,.recent').on('click', '.skipList', function (e) {
      e.preventDefault();
      // console.log(11);
      window.open('show.html?id=' + $(this).attr('id') + '&catename=' + $(this).attr('data-catename'));
    });
  }
  // 初始化swiper
  function swiper() {
    var mySwiper = new Swiper('.swiper', {
      // 无限循环
      loop: true,
      // 自动切换
      autoplay: {
        delay: 2000,
        stopOnLastSlide: false,
        disableOnInteraction: true,
      },
      // 如果需要前进后退按钮
      navigation: {
        nextEl: '.swiper-button-next',
        prevEl: '.swiper-button-prev',
      },
      pagination: {
        el: '.swiper-pagination',
        type: 'bullets',
      },
    });
  }
  // 时间函数
  function time(mesc) {
    let now = new Date(mesc);
    let year = getZero(now.getFullYear());
    let month = getZero(now.getMonth() + 1);
    let day = getZero(now.getDate());
    return year + '-' + month + '-' + day;
  }
  // 时间补零函数
  function getZero(num) {
    return num < 10 ? '0' + num : num;
  }
});
